package parsers.group;

import java.io.IOException;
import java.net.URL;
import java.util.List;

import dao.Linker;

import parsers.CommonMethods;

import model.Day;
import model.Group;
import model.Subject;
import model.Time;
import model.Warning;

import net.htmlparser.jericho.Element;
import net.htmlparser.jericho.HTMLElementName;
import net.htmlparser.jericho.Segment;
import net.htmlparser.jericho.Source;

public class GroupParser
{
	private Group group;
	
	public GroupParser(Group group)
	{
		this.group = group;
	}

	public Group parse(boolean linkWithParent) throws IOException
	{
		Source source = new Source(new URL(this.group.getLink()));
		
		Group group = null;
		
		if(linkWithParent)
		{
			group = this.group;
		}
		else
		{
			group = new Group(this.group.getName(), this.group.getDescription());
			group.setId(this.group.getId());
			group.setLink(CommonMethods.parseLink(this.group.getLink()));
		}
		
		Linker.groupList.add(group);
		
		List<Element> elements = source.getAllElements(HTMLElementName.TR);
		
		Day day = null;
		
		for (Element element : elements)
		{
			List<Element> e = element.getAllElements("b");
			for (Element element2 : e)
			{
				if(CommonMethods.checkDay(element2.getContent().toString()))
				{
					day = group.createDay(element2.getContent().toString());
				}
			}
			
			if(day != null)
			{
				e = element.getAllElements("tr");
				for (Element element2 : e)
				{
					Segment s = element2.getContent();
					List<Element> el = s.getAllElements("td");
					
					if(el.size() > 1)
					{
						Warning warning = new Warning(CommonMethods.parseElement(el.get(7)));
						Linker.warningRAWList.add(warning);
						Subject subject = day.createSubject(CommonMethods.checkSpace(el.get(0).getContent().toString()), new Time(CommonMethods.checkSpace(el.get(1).getContent().toString()), CommonMethods.checkSpace(el.get(2).getContent().toString())), el.get(3).getContent().toString(), el.get(4).getContent().toString(), warning);
						
						CommonMethods.parseTeachers(el.get(5), subject);
						CommonMethods.parseLectureRooms(el.get(6), subject);
					}
				}
			}
		}
		
		return group;
	}
	
	/*public static void main(String[] args) throws MalformedURLException, IOException
	{
		Group g = new Group("321 IDZ", "Informatyka stacjonarne-dzienne pierwszego stopnia z tyt. inżyniera");
		g.setLink("file:/D:/test3.html");
		GroupParser gp = new GroupParser(g);
		Group newGroup = gp.parse(true);
		System.out.println(g);
	}*/
}
